#include <d3d9.h>
#include <d3dx9.h>
#include <iostream>
#include <string.h>
#include "Gamefile.h"
#include <time.h>

#include <iostream>
#pragma comment( lib, "lua51.lib")

using namespace std;

const int FRAMES_PER_SECOND = 100;
const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;
DWORD next_game_tick = GetTickCount();

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	CoInitializeEx( NULL, COINIT_MULTITHREADED );
	bool Run = true;

	Gamefile Game;

	if(!Game.Game_Init(hInstance, nCmdShow))
		Run = false;

	int sleep_time = 0;

	/* initialize random seed: */
	srand ((unsigned)time(NULL));
	
	while(Run)
	{
		
		Game.update();

		MSG msg = {0};
		if(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			if(msg.message == WM_QUIT)
				Run = false;

			TranslateMessage(&msg);
			DispatchMessage(&msg);

		} 
	
		if(!Game.Run_Game())
			Run = false;

		//Escape-key ends program
		if (GetAsyncKeyState(VK_ESCAPE)) Run = false;

		next_game_tick += SKIP_TICKS;
        sleep_time = next_game_tick - GetTickCount();

		if( sleep_time >= 0 )
            Sleep( sleep_time );
	}

	Game.Shutdown();
	CoUninitialize();
	return 0;
}